package com.marsrover;

import java.util.HashMap;
import java.util.Map;

import com.marsrover.command.Command;
import com.marsrover.command.MoveCommand;
import com.marsrover.command.TurnLeftCommand;
import com.marsrover.command.TurnRightCommand;

public class Rover {
	private static final char TURN_LEFT = 'L';
	private static final char TURN_RIGHT = 'R';
	private static final char MOVE = 'M';

	private Location location;
	private String commands = "";
	private Map<Character, Command> commandExecutors = new HashMap<Character, Command>();

	public Rover(Plateau plateau, Location location) {
		this.location = location;

		commandExecutors.put(TURN_LEFT, new TurnLeftCommand(location));
		commandExecutors.put(TURN_RIGHT, new TurnRightCommand(location));
		commandExecutors.put(MOVE, new MoveCommand(location, plateau));
	}

	public void setCommands(String commands) {
		if (!commands.matches("[LRM]+")) {
			throw new CommandFormatException();
		}

		this.commands = commands;
	}

	public void executeCommands() {
		for (char cmdKey : commands.toCharArray()) {
			selectCommandExecutor(cmdKey).execute();
		}
	}

	private Command selectCommandExecutor(char command) {
		return commandExecutors.get(command);
	}

	public Location getLocation() {
		return location;
	}

	@Override
	public String toString() {
		return location.toString();
	}
}
